/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.autocode.manager.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.ksplatform.base.service.BaseService;
import cn.com.ksplatform.modules.autocode.manager.model.Module;
import cn.com.ksplatform.modules.autocode.manager.model.Project;
import cn.com.ksplatform.modules.autocode.manager.model.Sence;
import cn.com.ksplatform.modules.autocode.util.XmlUtil;

/**
 * ClassName:ProjectService.java <br/>
 * Date: 2015年11月3日 <br/>
 * 
 * @author Mr.Xiao
 * @version 1.0
 */
@Component("modules.autocode.ProjectService")
public class ProjectService extends BaseService{
	
	@Autowired
	SenceService senceService;
	
	public void saveProject(Project project) throws FileNotFoundException {
		File bulidPath = new File(project.getBulidPath());
		if(!bulidPath.exists()){
			bulidPath.mkdirs();
		}
		XmlUtil.saveObject2Xml(project, new FileOutputStream(project.getBulidPath()+File.separator+project.getProjectName()+".xml"));
	}

	public Project getProject(String bulidPath) throws FileNotFoundException {
		Project project = (Project) XmlUtil.getObjectFromXml(Project.class, new FileInputStream(bulidPath));
		//添加业务模块
		File[] fs = new File(project.getBulidPath()).listFiles();
		List<Module> modules = new ArrayList<Module>();
		for(File f : fs){
			if(f.isDirectory()){
				File moduleXml = new File(f.getPath()+File.separator+"module.xml");
				if(moduleXml.exists()){
					Module module = (Module) XmlUtil.getObjectFromXml(Module.class, new FileInputStream(moduleXml));
					module.setProject(project);
					List<Sence> sences = senceService.getSencesByModule(module);
					module.setSences(sences);
					modules.add(module);
				}
			}
		}
		project.setModules(modules);
		return project;
	}
	
}
